<template>
  <div class="app-container">
    <el-form label-width="100" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="诊所名称" prop="clinicName">
        <el-input
            v-model="queryParams.clinicName"
            placeholder="请输入诊所名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人姓名" prop="ownerName">
        <el-input
            v-model="queryParams.ownerName"
            placeholder="请输入负责人姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="诊所状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择诊所状态" clearable>
          <el-option
              v-for="dict in sys_status_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!---上面是搜索,下面是按钮------------------------------------------------------------------------------------->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:clinics:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:clinics:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:clinics:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:clinics:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--表格----------------------------------------------------------------------------------------->
    <el-table v-loading="loading" :data="clinicsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="诊所编号" align="center" prop="clinicId"/>
      <el-table-column label="诊所名称" align="center" prop="clinicName"/>
      <el-table-column label="负责人姓名" align="center" prop="ownerName"/>
      <el-table-column label="负责人电话" align="center" prop="ownerPhone"/>
      <el-table-column label="负责人邮箱" align="center" prop="ownerEmail"/>
      <el-table-column label="地址" align="center" prop="address"/>
      <el-table-column label="详细地址" align="center" prop="detailedAddress"/>
      <el-table-column label="诊所介绍" align="center" prop="introduction"/>
      <el-table-column label="诊所状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_status_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" align="center" prop="expiryTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expiryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总用户数" align="center" prop="totalUsers"/>
      <el-table-column label="创建时间" align="center" prop="creationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间" align="center" prop="lastUpdated" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastUpdated, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="诊所logo(点击图片修改)" width="100">
        <template v-slot="scope">
          <!-- 自定义文件上传按钮  class="custom-file-button"-->
          <label v-if="clinicsList" :for="'fileInput' + scope.$index">
            <img width="80" :src="clinicsList[scope.$index].logo"
                 alt="添加logo">
          </label>
          <!-- 原生文件输入框，设置为透明并绝对定位到屏幕外 -->
          <input type="file" @change="uploadMyImage($event, scope.$index)"
                 style="opacity: 0; position: absolute; left: -9999px;" :id="'fileInput' + scope.$index">
        </template>
      </el-table-column>
      <el-table-column width="180" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:clinics:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:clinics:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改诊所信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="clinicsRef" :model="form" :rules="rules" label-width="250px">
        <el-form-item label="诊所名称" prop="clinicName">
          <el-input v-model="form.clinicName" placeholder="请输入诊所名称"/>
        </el-form-item>
        <el-form-item label="诊所所有人姓名" prop="ownerName">
          <el-input v-model="form.ownerName" placeholder="请输入诊所所有人姓名"/>
        </el-form-item>
        <el-form-item label="诊所所有人电话" prop="ownerPhone">
          <el-input v-model="form.ownerPhone" placeholder="请输入诊所所有人电话"/>
        </el-form-item>
        <el-form-item label="诊所所有人邮箱" prop="ownerEmail">
          <el-input v-model="form.ownerEmail" placeholder="请输入诊所所有人邮箱"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-cascader
              :options="pcTextArr"
              @change="handleChangeAdress"
              v-model="address"
              placeholder="请选择地址"
          />
          <!--          <el-input v-model="form.address" placeholder="请输入地址" />-->
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址"/>
        </el-form-item>
        <el-form-item label="诊所介绍" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="诊所状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_status_type"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="到期时间" prop="expiryTime">
          <el-date-picker clearable
                          v-model="form.expiryTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总用户数" prop="totalUsers">
          <el-input v-model="form.totalUsers" placeholder="请输入总用户数"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Clinics">
import {listClinics, getClinics, delClinics, addClinics, updateClinics, formatDateTime,changeFavicon} from "@/api/system/clinics";
import {pcTextArr} from 'element-china-area-data';
import request from "@/utils/request.js";

const {proxy} = getCurrentInstance();
const {sys_status_type} = proxy.useDict('sys_status_type');
const address = ref([]);

function handleChangeAdress(value) {
  // 假设 value 是一个数组，例如：["广东省", "广州市", "越秀区"]
  if (Array.isArray(value) && value.length > 0) {
    // 将数组连接成一个字符串，例如："广东省广州市越秀区"
    form.value.address = value.join('/');
  } else {
    // 如果没有选择任何值，清空地址字段
    form.value.address = '';
  }
}




const uploadMyImage = (event, index) => {
  const files = event.target.files;
  if (files.length === 0) {
    console.log('没有文件被选择');
    return;
  }
  const formData = new FormData();
  formData.append('file', files[0]);
  console.log(files[0]);
  if (files[0].name.substring(files[0].name.lastIndexOf('.') + 1) !== "ico") {
    proxy.$modal.msgError("请上传ico格式的图片");
    return;
  }


  let OldLogoUrl = clinicsList.value[index].logo;//存老地址,如果数据修改成功，则删除
  let NewLogoUrl = "1";//新图片地址
//请求图片上传接口
  request({
    url: '/file/upload',
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: formData
    //请求图片上传接口成功
  }).then(response => {
    clinicsList.value[index].logo = response.msg;
    clinicsList.value[index].lastUpdated = formatDateTime(new Date());
    NewLogoUrl = response.msg;
    console.log('上传成功:');
    console.log(response);
    //请求诊所信息修改接口
    request({
      url: '/system/clinics',
      method: 'put',
      data: clinicsList.value[index]
      //请求诊所信息修改接口成
    }).then(res => {
      console.log('上传成功' + res.msg);
      // 调用函数保存文件
      // saveFile(files[0], savePath);
      if(clinicsList.value[index].status==1){
        changeFavicon(NewLogoUrl)
      }
      console.log(res);
      //请求图片删除接口(删除原有图片)
      request({
        url: '/file/delete',
        method: 'delete',
        params: {url: OldLogoUrl}
        //请求图片删除接口成功
      }).catch(error => {
        console.error('旧地址删除失败', error);
      })

      //请求诊所信息修改接口失败
    }).catch(error => {
      console.error('上传失败', error);


      //请求图片删除接口
      request({
        url: '/file/delete',
        method: 'delete',
        params: {url: NewLogoUrl}
        //请求图片删除接口成功
      }).catch(error => {
        console.error('新地址删除失败', error);
      })


    })
    //请求图片上传接口失败
  }).catch(error => {
    console.error('上传失败', error);
  });
}
const clinicsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    clinicName: null,
    ownerName: null,
    ownerPhone: null,
    ownerEmail: null,
    address: null,
    detailedAddress: null,
    introduction: null,
    status: null,
    expiryTime: null,
    totalUsers: null,
    creationTime: null,
    lastUpdated: null
  },
  rules: {
    clinicName: [
      {required: true, message: "诊所名称不能为空", trigger: "blur"}
    ],
    ownerName: [
      {required: true, message: "诊所所有人姓名不能为空", trigger: "blur"}
    ],
    ownerPhone: [
      {required: true, message: "诊所所有人电话不能为空", trigger: "blur"}
    ],
    ownerEmail: [
      {required: true, message: "诊所所有人邮箱不能为空", trigger: "blur"}
    ],
    address: [
      {required: true, message: "地址不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "诊所状态不能为空", trigger: "change"}
    ],
    expiryTime: [
      {required: true, message: "到期时间不能为空", trigger: "blur"}
    ],
    totalUsers: [
      {required: true, message: "总用户数不能为空", trigger: "blur"}
    ],
    creationTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

// /** 查询诊所信息管理列表 */
// function getList() {
//   loading.value = true;
//   listClinics(queryParams.value).then(response => {
//     console.log(JSON.stringify(response))
//     clinicsList.value = response.rows;
//     total.value = response.total;
//     loading.value = false;
//   }).catch(() => {
//     loading.value = false;
//   });
// }
/** 查询诊所信息管理列表 */
function getList() {
  loading.value = true;
  listClinics(queryParams.value).then(response => {
    console.log(JSON.stringify(response))
    clinicsList.value = response.rows;
    total.value = response.total;
    // 检查所有诊所状态是否都为0，如果是，则将第一个诊所状态改为1
    let allStatusZero = clinicsList.value.every(clinic => clinic.status == 0);
    console.log(allStatusZero)
    if (allStatusZero && clinicsList.value.length > 0) {
      const firstClinic = clinicsList.value[0];
      firstClinic.status = '1';
      updateClinics(firstClinic).then(() => {
        changeFavicon(clinicsList.value[0].logo)
        console.log('第一个诊所状态更新为1');
      }).catch(error => {
        console.error('更新第一个诊所状态失败', error);
      });
    }
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    clinicId: null,
    clinicName: null,
    ownerName: null,
    ownerPhone: null,
    ownerEmail: null,
    address: null,
    detailedAddress: null,
    introduction: null,
    status: null,
    expiryTime: null,
    totalUsers: null,
    creationTime: null,
    lastUpdated: null
  };
  address.value=null;
  proxy.resetForm("clinicsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.clinicId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加诊所信息管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  console.log(JSON.stringify(row))
  address.value = row.address.split("/")
  const _clinicId = row.clinicId || ids.value
  getClinics(_clinicId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改诊所信息管理";
  });
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["clinicsRef"].validate(valid => {
    if (valid) {
      if (form.value.clinicId != null) {
        form.value.lastUpdated = formatDateTime(new Date());
        console.log(JSON.stringify(form.value))
        //当前修改对象为开启
        if(form.value.status == 1){
          //将其余设置为禁用
          updateClinicStatus();
        }
        updateClinics(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch((e) => {
          open.value = false;
          console.log(e)
        });
      } else {
        //当前新增对象为开启
        if(form.value.status == 1){
          //将其余设置为禁用
          updateClinicStatus();
        }
        form.value.creationTime = formatDateTime(new Date());
        console.log(form.value)
        addClinics(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch((e) => {
          open.value = false;
          console.log(e)
        });
      }
    }
  });
}
function updateClinicStatus() {
  // 更新其他诊所的状态为0
  listClinics(queryParams.value).then(response => {
    const otherClinics = response.rows.filter(clinic => clinic.clinicId !== form.value.clinicId);
    otherClinics.forEach(clinic => {
      if(clinic.status ==1){
        clinic.status = '0';
        updateClinics(clinic).then(() => {
          console.log('其他诊所状态更新成功');
        }).catch(error => {
          console.error('其他诊所状态更新失败', error);
        });
      }
    });
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _clinicIds = row.clinicId || ids.value;
  proxy.$modal.confirm('是否确认删除诊所信息管理编号为"' + _clinicIds + '"的数据项？').then(function () {
    return delClinics(_clinicIds);
  }).then(() => {
    console.log(row)
    if (row.logo) {
      request({
        url: '/file/delete',
        method: 'delete',
        params: {url: row.logo}
      }).then(() => {
        console.log('旧地址删除成功');
      }).catch(error => {
        console.error('旧地址删除失败', error);
      });
    }
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/clinics/export', {
    ...queryParams.value
  }, `clinics_${new Date().getTime()}.xlsx`)
}

getList();
</script>
